package com.example.demo.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * Created by shangfei on 2018/7/10.
 */
public class Server
{
    public static void main(String[] args) throws InterruptedException {
        //1、接收连接请求
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        //2、实际的业务处理操作
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        //3、创建一个辅助类bootstrap，对Server进行一系列配置
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        //把两个工作线程组加入进来
        serverBootstrap.group(bossGroup,workerGroup)
                .channel(NioServerSocketChannel.class)//指定使用NioServerSocketChannel类型的通道
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new ServerHandler());
                    }
                })
                //
                .option(ChannelOption.SO_BACKLOG,128)
                //
                .childOption(ChannelOption.SO_KEEPALIVE,true);

        ChannelFuture channelFuture = serverBootstrap.bind(8765).sync();

        channelFuture.channel().closeFuture().sync();

        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
